package com.lanou.myim.adapter;

import android.content.Context;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.lanou.myim.R;
import com.lanou.myim.application.BaseApplication;
import com.lanou.myim.tools.BitmapUtils;
import com.lanou.myim.tools.ParseSingleton;
import com.lanou.myim.tools.PlayRecordingUtils;
import com.lanou.myim.tools.VolleySingleton;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by dllo on 16/3/10.
 */
public class PrivateChatActivityAdapter extends RecyclerView.Adapter {
    private Context context;
    private List<EMMessage> messages;
    private PlayRecordingUtils playRecordingUtils;
    private boolean isPlaying = false;
    private boolean isPlayingSend = false;
    private AnimationDrawable animationDrawable;
    private AnimationDrawable animationDrawableSend;
    private Handler handler;
    private Thread thread;
    private Thread threadSend;
    private Html.ImageGetter imageGetter;
    String imageCacheDir = Environment.getExternalStorageDirectory().getAbsolutePath()
            +"/Android/data/com.lanou.myim/easemob-demo#chatdemoui/"
            + EMChatManager.getInstance().getCurrentUser()+"/image";
    public PrivateChatActivityAdapter(final Context context,List<EMMessage> messages) {
        this.context = context;
        this.messages = messages;
        playRecordingUtils = new PlayRecordingUtils();
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 0) {
                    animationDrawable.stop();
                    isPlaying = false;
                    ((VoiceViewHolder) msg.obj).voicePictureIv.setBackgroundResource(R.drawable.ease_chatfrom_voice_playing);
                }else if (msg.what ==1 ){
                    animationDrawableSend.stop();
                    isPlayingSend = false;
                    ((VoiceViewHolder) msg.obj).voicePictureIv.setBackgroundResource(R.drawable.ease_chatto_voice_playing);
                }
                return false;
            }
        });

        imageGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                int id = Integer.parseInt(source);
                Drawable d = context.getResources().getDrawable(id);
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                return d;
            }
        };


    }

    @Override
    public int getItemCount() {
        return messages.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1){
            View view = LayoutInflater.from(context).inflate(R.layout.item_recycleview_receive_text,null);
            TextViewHolder holder = new TextViewHolder(view);
            return holder;
        }else if (viewType == 0){
            View view = LayoutInflater.from(context).inflate(R.layout.item_recycleview_send_text,null);
            TextViewHolder holder = new TextViewHolder(view);
            return holder;
        }else if (viewType == 3){
            View view = LayoutInflater.from(context).inflate(R.layout.item_recycleview_send_picture,null);
            PictureViewHolder holder = new PictureViewHolder(view);
            return holder;
        }else if (viewType == 4){
            View view = LayoutInflater.from(context).inflate(R.layout.item_recycleview_receive_picture,null);
            PictureViewHolder holder = new PictureViewHolder(view);
            return holder;
        }else if (viewType == 5){
            View view = LayoutInflater.from(context).inflate(R.layout.item_recycleview_send_voice,null);
            VoiceViewHolder holder = new VoiceViewHolder(view);
            return holder;
        }else if (viewType == 6){
            View view = LayoutInflater.from(context).inflate(R.layout.item_recycleview_receive_voice,null);
            VoiceViewHolder holder = new VoiceViewHolder(view);
            return holder;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
       if (getItemViewType(position) == 0||getItemViewType(position) == 1){
           ParseSingleton.setBitmap(messages.get(position).getFrom()
                   , ((TextViewHolder) holder).pictureIv);
           final Date date = new Date(messages.get(position).getMsgTime());
           SimpleDateFormat myFmt=new SimpleDateFormat("a hh:mm");
           ((TextViewHolder)holder).timeIv.setText(myFmt.format(date));
           String content = messages.get(position).getBody().toString();
           int length = content.length();
           content = content.substring(5, length - 1);
           ((TextViewHolder) holder).contentTv.setText(Html.fromHtml(content,imageGetter, null));
       }else if (getItemViewType(position) == 4){
           final Date date = new Date(messages.get(position).getMsgTime());
           SimpleDateFormat myFmt=new SimpleDateFormat("a hh:mm");
           ((PictureViewHolder)holder).timeIv.setText(myFmt.format(date));
           ParseSingleton.setBitmap(messages.get(position).getFrom(), ((PictureViewHolder) holder).headPicture);
           final String content = messages.get(position).getBody().toString();
           String localUrl = content.substring(content.indexOf("/storage"),content.indexOf(",remote"));
           final String url1 = content.substring(content.lastIndexOf("http://"));
//           ((PictureViewHolder)holder).contentPicture.setImageBitmap(BitmapUtils.getLoacalBitmap(localUrl, 100, 100));
           final String fileName = content.substring(content.lastIndexOf("/"));
           VolleySingleton.getInstance().addImageRequest(url1,fileName,context,((PictureViewHolder)holder).contentPicture);
                   ((PictureViewHolder) holder).contentPicture.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   Intent intent = new Intent();
                   intent.setAction(Intent.ACTION_VIEW);
                   File file  = new File(imageCacheDir+fileName);
                   intent.setDataAndType(Uri.fromFile(file), "image/*");
                   context.startActivity(intent);
               }
           });

       }else if (getItemViewType(position) == 3){
           final Date date = new Date(messages.get(position).getMsgTime());
           SimpleDateFormat myFmt=new SimpleDateFormat("a hh:mm");
           ((PictureViewHolder)holder).timeIv.setText(myFmt.format(date));
           ParseSingleton.setBitmap(messages.get(position).getFrom(), ((PictureViewHolder) holder).headPicture);
           String content = messages.get(position).getBody().toString();
           final String localUrl = content.substring(content.indexOf("/storage"),content.indexOf(",remote"));
           ((PictureViewHolder)holder).contentPicture.setImageBitmap(BitmapUtils.getLoacalBitmap(localUrl,100,100));
           ((PictureViewHolder)holder).contentPicture.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   Intent intent = new Intent();
                   intent.setAction(Intent.ACTION_VIEW);
                   File file  = new File(localUrl);
                   intent.setDataAndType(Uri.fromFile(file), "image/*");
                   context.startActivity(intent);
               }
           });
       }else if (getItemViewType(position) == 6){
           ParseSingleton.setBitmap(messages.get(position).getFrom(), ((VoiceViewHolder) holder).headPictureIv);
           final Date date = new Date(messages.get(position).getMsgTime());
           SimpleDateFormat myFmt=new SimpleDateFormat("a hh:mm");
           ((VoiceViewHolder) holder).timeIv.setText(myFmt.format(date));
           String body = messages.get(position).getBody().toString();
           final String path = body.substring(body.indexOf("/storage"), body.indexOf(",remote"));
           final String time = body.substring(body.lastIndexOf(":") + 1);
           ((VoiceViewHolder)holder).timeLengthTV.setText(time+"''");
           ((VoiceViewHolder)holder).voicePictureIv.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   if (animationDrawableSend != null&&animationDrawableSend.isRunning()){
                       animationDrawableSend.stop();
                       playRecordingUtils.stopPlaying();
                       if (threadSend != null){
                           threadSend.interrupt();
                       }
                   }
                   ((VoiceViewHolder)holder).unreadiv.setVisibility(View.GONE);
                   if (!isPlaying){
                   animationDrawable = (AnimationDrawable) context.getResources().getDrawable(R.drawable.anim_voice_from_icon);
                       ((VoiceViewHolder)holder).voicePictureIv.setBackground(animationDrawable);
                   animationDrawable.start();
                       thread = new Thread(new Runnable() {
                           @Override
                           public void run() {
                               try {
                                   Thread.sleep(Integer.parseInt(time)*1000);
                               } catch (InterruptedException e) {
                                   e.printStackTrace();
                               }
                               Message msg = new Message();
                               msg.what = 0;
                               msg.obj = (VoiceViewHolder)holder;
                               handler.sendMessage(msg);
                           }
                       });
                       thread.start();
                       playRecordingUtils.startPlaying(path);
                       isPlaying = true;
                   }else {
                       animationDrawable.stop();
                       playRecordingUtils.stopPlaying();
                       isPlaying = false;
                       thread.interrupt();
                       ((VoiceViewHolder)holder).voicePictureIv.setBackgroundResource(R.drawable.ease_chatfrom_voice_playing);
                   }
               }
           });

       }else if (getItemViewType(position) == 5){
           ParseSingleton.setBitmap(messages.get(position).getFrom(), ((VoiceViewHolder) holder).headPictureIv);
           final Date date = new Date(messages.get(position).getMsgTime());
           SimpleDateFormat myFmt=new SimpleDateFormat("a hh:mm");
           ((VoiceViewHolder) holder).timeIv.setText(myFmt.format(date));
           String body = messages.get(position).getBody().toString();
           final String path = body.substring(body.indexOf("/storage"), body.indexOf(",remote"));
           final String time = body.substring(body.lastIndexOf(":") + 1);
           ((VoiceViewHolder)holder).timeLengthTV.setText(time+"''");
           ((VoiceViewHolder)holder).voicePictureIv.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   if (animationDrawable != null&&animationDrawable.isRunning()){
                       animationDrawable.stop();
                       playRecordingUtils.stopPlaying();
                       if (thread != null){
                           thread.interrupt();
                       }
                   }
                   if (!isPlayingSend){
                       animationDrawableSend = (AnimationDrawable) context.getResources().getDrawable(R.drawable.anim_voice_to_icon);
                       ((VoiceViewHolder)holder).voicePictureIv.setBackground(animationDrawableSend);
                       animationDrawableSend.start();
                       threadSend = new Thread(new Runnable() {
                           @Override
                           public void run() {
                               try {
                                   Thread.sleep(Integer.parseInt(time)*1000);
                               } catch (InterruptedException e) {
                                   e.printStackTrace();
                               }
                               Message msg = new Message();
                               msg.what = 1;
                               msg.obj = (VoiceViewHolder)holder;
                               handler.sendMessage(msg);
                           }
                       });
                       threadSend.start();
                       playRecordingUtils.startPlaying(path);
                       isPlayingSend = true;
                   }else {
                       animationDrawableSend.stop();
                       playRecordingUtils.stopPlaying();
                       isPlayingSend = false;
                       threadSend.interrupt();
                       ((VoiceViewHolder)holder).voicePictureIv.setBackgroundResource(R.drawable.ease_chatto_voice_playing);
                   }
               }
           });
       }



    }

    @Override
    public int getItemViewType(int position) {
        if (messages.get(position).getType().toString().equals("TXT")
                &&messages.get(position).getFrom().equals(EMChatManager.getInstance().getCurrentUser())){
            return 0;
        }else if (messages.get(position).getType().toString().equals("TXT")){
            return 1;
        }else if(messages.get(position).getType().toString().equals("IMAGE")
                &&messages.get(position).getFrom().equals(EMChatManager.getInstance().getCurrentUser())){
            return 3;
        }else if (messages.get(position).getType().toString().equals("IMAGE")){
            return 4;
        }else if (messages.get(position).getType().toString().equals("VOICE")
                &&messages.get(position).getFrom().equals(EMChatManager.getInstance().getCurrentUser())){
            return 5;
        }else if (messages.get(position).getType().toString().equals("VOICE")){
            return 6;
        }
        return -1;
    }


    public void refreshData(List<EMMessage> messages){
        this.messages = messages;
        notifyDataSetChanged();
    }

    class TextViewHolder extends RecyclerView.ViewHolder{
        private TextView timeIv;
        private ImageView pictureIv;
        private TextView contentTv;

        public TextViewHolder(View itemView) {
            super(itemView);
            timeIv = (TextView) itemView.findViewById(R.id.timestamp);
            pictureIv = (ImageView) itemView.findViewById(R.id.iv_userhead);
            contentTv = (TextView) itemView.findViewById(R.id.tv_chatcontent);
        }

    }
    class PictureViewHolder extends RecyclerView.ViewHolder{
        private TextView timeIv;
        private ImageView headPicture;
        private ImageView contentPicture;
        public PictureViewHolder(View itemView) {
            super(itemView);
            timeIv = (TextView) itemView.findViewById(R.id.timestamp);
            headPicture = (ImageView) itemView.findViewById(R.id.iv_userhead);
            contentPicture = (ImageView) itemView.findViewById(R.id.image);
        }
    }
    class VoiceViewHolder extends RecyclerView.ViewHolder{
        private TextView timeIv;
        private TextView timeLengthTV;
        private ImageView headPictureIv;
        private ImageView voicePictureIv;
        private ImageView unreadiv;

        public VoiceViewHolder(View itemView) {
            super(itemView);
            timeIv = (TextView) itemView.findViewById(R.id.timestamp);
            timeLengthTV = (TextView) itemView.findViewById(R.id.tv_length);
            headPictureIv = (ImageView) itemView.findViewById(R.id.iv_userhead);
            voicePictureIv = (ImageView) itemView.findViewById(R.id.iv_voice);
            unreadiv = (ImageView) itemView.findViewById(R.id.iv_unread_voice);
        }
    }



}

